import base64
import os
import random

from django.core.paginator import Paginator
from django.db.models import F
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.views.decorators.cache import cache_control, cache_page

from . import forms
from . import models

# Create your views here.

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


@cache_control(max_age=24 * 60 * 60, public=True)
def index(request):
    models.ClickTimes.objects.filter(id=0).update(times=F('times') + random.randint(1, 10))

    user_data = models.ClickTimes.objects.get(id=0)
    project_class = models.ProjectClass.objects.all()
    projects = models.Projects.objects.all()
    connect_us = models.ConnectionUs.objects.get(web_posi='主页')

    content = {
        "user_data": user_data,
        "project_class": project_class,
        "projects": projects,
        "connect_us": connect_us
    }
    return render(request, 'web_index.html', content)


def index_(request):
    format_form = forms.DataForm(request.GET)
    if format_form.is_valid():
        name = format_form.cleaned_data['name']
        tel = format_form.cleaned_data['tel']
        text = format_form.cleaned_data['text']
        res = models.UserData.objects.get_or_create(name=name, tel=tel, text=text)
        if res[1]:
            # models.ClickTimes.objects.filter(id=0).update(times=F('times') + 1)
            return JsonResponse('预约成功', safe=False)
        else:
            return JsonResponse('姓名：{}。\n手机号：{}。\n\n我们已收到您的预约。\n平台火爆，程序猿正在奔跑赶来路上。'.format(name, tel), safe=False)
    else:
        return JsonResponse('输入有误，预约失败。', safe=False)


@cache_control(max_age=24 * 60 * 60, public=True)
def get_pro_class(request):
    project_class = list(models.ProjectClass.objects.all().values('id', 'name'))
    return JsonResponse(project_class, safe=False)


# js中无法用url获取
@cache_control(max_age=24 * 60 * 60, public=True)
def get_pic(request, tag, page):
    print(request.GET)

    # 获取分类数据
    if int(tag) == 1:
        pj_data = models.Projects.objects.all()
    else:
        pj_data = models.Projects.objects.filter(belong_class=int(tag)).order_by("-id")

    # 分页
    pgnt = Paginator(pj_data, 6)
    res_data_tmp = pgnt.page(page)

    # 获取分页后数据
    res_data = [{"num_pages": pgnt.num_pages}]
    for i in res_data_tmp:
        with open(os.path.join(BASE_DIR, 'upload') + '/' + str(i.pic), 'rb') as pic:
            res_data.append({"title": i.title, "pic": 'data:image/png;base64,' + str(
                base64.b64encode(pic.read()).decode("utf-8", "ignore"))})

    return JsonResponse(res_data, safe=False)


@cache_control(max_age=24 * 60 * 60, public=True)
def get_pic_2(request):
    tag = request.GET.get("tag", 1)
    page = request.GET.get("page", 1)

    # 获取分类数据
    if int(tag) == 1:
        pj_data = models.Projects.objects.all()
    else:
        pj_data = models.Projects.objects.filter(belong_class=int(tag)).order_by("-id")

    # 分页
    pgnt = Paginator(pj_data, 6)
    res_data_tmp = pgnt.page(page)

    # 获取分页后数据
    res_data = [{"num_pages": pgnt.num_pages}]
    for i in res_data_tmp:
        tmp_data = {}
        with open(os.path.join(BASE_DIR, 'upload') + '/' + str(i.pic), 'rb') as pic:
            tmp_data.update({"title": i.title, "pic": 'data:image/png;base64,' + str(
                base64.b64encode(pic.read()).decode("utf-8", "ignore"))})
        try:
            tmp_data['detail'] = i.projectdetail.id
        except:
            tmp_data.update({'detail': None})

        res_data.append(tmp_data)

    return JsonResponse(res_data, safe=False)


@cache_control(max_age=24 * 60 * 60, public=True)
def get_content(request):
    # 获取数据
    con_id = request.GET.get('content_id', 1)
    pd_data = models.ProjectDetail.objects.get(id=con_id)

    # 加码base64
    res_data = pd_data
    return JsonResponse(
        {
            "name": res_data.name,
            "project": res_data.belong_pro.belong_class.name,
            "language": res_data.belong_language.language,
            "database": res_data.belong_database.database,
            "content": res_data.content,
        },
        safe=False
    )


def detail(request):
    return render(request, 'detail.html')


def test(request):
    return render(request, 'test_index.html')
